package com.smarthome.common.tools;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class CookieUtils {

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie cookies[] = request.getCookies();
        if (cookies == null || name == null) {
            return null;
        }
        Cookie cookie = null;
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(name)) {
                cookie = cookies[i];
                // TODO
                if (request.getServerName().equals(cookie.getDomain())) {
                    break;
                }
            }
        }
        return cookie;
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, Cookie... cookies) {
        if (cookies != null) {
            for (Cookie e : cookies) {
                if (cookieName.equals(e.getName())) {
                    deleteCookie(request, response, e);
                }
            }
        }
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, Cookie cookie) {
        if (cookie != null) {
            String path = StringUtils.isBlank(request.getContextPath()) ? "/" : request.getContextPath();
            cookie.setPath(path);
            cookie.setValue("");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
        setCookie(request, response, name, value, 60 * 60 * 24 * 30);
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {
        if (value == null) {
            value = "";
        }
        String path = StringUtils.isBlank(request.getContextPath()) ? "/" : request.getContextPath();
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        response.addCookie(cookie);
    }
}
